import time
import logging

from django.http import JsonResponse
from rest_framework.response import Response

log = logging.getLogger('lamp')

error_message = {
    # 系统消息
    200: "请求成功",
    403: "无权限访问资源",
    404: "API Not Fund",
    405: "方式不被允许",
    500: "请求处理失败",
    600: "系统繁忙,请稍后再试",
}


def json_404(request, **_):
    """ Django框架404返回json格式定义
    """
    log.warning("%s '%s' 404" % (request.method, request.path))
    return JsonResponse({
        'timestamp': int(time.time()),
        'respCode': 404,
        'respMsg': 'API Not Fund',
        'result': {}
    })


def json_response(code=200, body=None, message="", extend=None, headers=None):
    """ 通用json响应方法

    :param code: 响应码
    :param body: 响应主体
    :param message: 响应的错误消息
    :param extend: 基础参数扩展
    :param headers: 扩展请求头
    """
    result = {
        'timestamp': int(time.time()),
        'respCode': code,
        'respMsg': message,
        'result': body if body is not None else {}
    }

    # 若追加了其他参数则合并
    if extend and isinstance(extend, dict):
        result = dict(result, **extend)

    # 请求头
    if (headers is not None) and (not isinstance(headers, dict)):
        headers = {}

    return Response(data=result, headers=headers)


def json_success(body=None, extend=None, headers=None):
    """ 响应正确内容

    :param body: 响应体
    :param extend: 扩展参数
    :param headers: 响应头参数
    """
    return json_response(body=body, message=error_message.get(200, '请求成功'), extend=extend, headers=headers)


def json_fail(code=500, message=None, body=None, extend=None, headers=None):
    """ 请求出错响应

    :param code: 响应错误识别码
    :param message: 错误友好提示内容
    :param body: 响应体
    :param extend: 扩展参数
    :param headers: 响应头参数
    """
    if not message:
        message = error_message.get(code, '请求处理失败')

    return json_response(code, body={} if body is None else body, message=message, extend=extend, headers=headers)
